package com.salton123.soulove

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.IntentFilter
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.fanjun.keeplive.KeepLive
import com.fanjun.keeplive.config.ForegroundNotification
import com.fanjun.keeplive.config.ForegroundNotificationClickListener
import com.fanjun.keeplive.config.KeepLiveService
import com.hjq.toast.ToastUtils
import com.salton123.api.IApplicationProvider
import com.salton123.app.BaseApplication
import com.salton123.charging.receiver.BatteryStatusReceiver
import com.salton123.charging.receiver.BootReceiver
import com.salton123.charging.receiver.ReStarter
import com.salton123.charging.service.SoundService
import com.salton123.charging.util.PrefsUtils
import com.salton123.qa.QualityAssistant.install
import com.salton123.qa.QualityContext
import com.salton123.soulove.app.R
import com.salton123.soulove.common.BuildConfig
import com.salton123.soulove.common.widget.TRefreshHeader
import com.salton123.soulove.sdk.ThirdHelper
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter

/**
 * User: newSalton@outlook.com
 * Date: 2019/5/23 15:40
 * ModifyTime: 15:40
 * Description:
 */
class XApp : BaseApplication() {
    companion object {
        init {
            //设置全局默认配置（优先级最低，会被其他设置覆盖）
            SmartRefreshLayout.setDefaultRefreshInitializer { _: Context?, layout: RefreshLayout? ->
                //开始设置全局的基本参数（可以被下面的DefaultRefreshHeaderCreator覆盖）
                layout?.setHeaderMaxDragRate(1.5f)
            }
            //设置全局的Header构建器
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context: Context?, _: RefreshLayout? ->
                TRefreshHeader(context)
            }
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context: Context?, _: RefreshLayout? ->
                val classicsFooter = ClassicsFooter(context)
                classicsFooter.setTextSizeTitle(12f)
                classicsFooter.setDrawableSize(16f)
                classicsFooter.setFinishDuration(0)
                classicsFooter
            }
        }
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        ToastUtils.init(this)
        ThirdHelper.getInstance(this)
                .initQualityAssistant()
                .initFragmentation(BuildConfig.APP_DEVELOP)
                .initRouter()
                .initUtils()
                .initBugly()
                .initCrashView()
        initQualityAssistant()
        ARouter.getInstance().navigation(IApplicationProvider::class.java)
                .getOnInitActions().forEach {
                    it.doAction()
                }
        if (isMain(this)) {
            PrefsUtils.init(this)
            initReceivers()
        }
    }

    fun initQualityAssistant() {
        install(QualityContext(this))
    }

    fun initReceivers() {
        registerReceiver(BootReceiver(), IntentFilter("android.intent.action.BOOT_COMPLETED"))
        registerReceiver(ReStarter(), IntentFilter(ReStarter.RESTART))
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED")
        intentFilter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED")
        intentFilter.addAction("android.intent.action.BATTERY_CHANGED")
        intentFilter.addAction("android.intent.action.BATTERY_LOW")
        val batteryStatusReceiver = BatteryStatusReceiver()
        registerReceiver(batteryStatusReceiver, intentFilter)
        //定义前台服务的默认样式。即标题、描述和图标
        val foregroundNotification =
                ForegroundNotification(getString(R.string.charge_tip), getString(R.string.you_are_charging),
                        R.drawable.ic_launcher_record,
                        //定义前台服务的通知点击事件
                        ForegroundNotificationClickListener { context, intent ->

                        })
        KeepLive.runMode = KeepLive.RunMode.ENERGY
        //启动保活服务
        KeepLive.startWork(this, KeepLive.RunMode.ENERGY, foregroundNotification,
                //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写
                object : KeepLiveService {
                    /**
                     * 运行中
                     * 由于服务可能会多次自动启动，该方法可能重复调用
                     */
                    override fun onWorking() {
                        SoundService.start(applicationContext)
                    }

                    /**
                     * 服务终止
                     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
                     */
                    override fun onStop() {
                    }
                }
        )
    }

    private fun isMain(application: Application): Boolean {
        val pid = android.os.Process.myPid()
        var processName = ""
        val mActivityManager = application.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcessInfos = mActivityManager.runningAppProcesses
        if (runningAppProcessInfos != null) {
            for (appProcess in mActivityManager.runningAppProcesses) {
                if (appProcess.pid == pid) {
                    processName = appProcess.processName
                    break
                }
            }
            val packageName = application.packageName
            if (processName == packageName) {
                return true
            }
        }
        return false
    }
}